package com.shop.daoImpl;

import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.shop.dao.MerchantDao;
import com.shop.entity.Goods;
import com.shop.entity.Merchant;
import com.shop.entity.MerchantAddress;
import com.shop.entity.MerchantInfor;
import com.shop.entity.MerchantOrder;

@Repository("merchantDaoImpl")
public class MerchantDaoImpl extends BaseDaoImpl<Merchant> implements MerchantDao {
	
	
	public MerchantDaoImpl() {
		super(Merchant.class) ;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Merchant findByUsername(String username) {
		/**
		 * from Merchant 中的Merchant需要使用类名称
		 */
		Query query = getSession().createQuery("from Merchant") ;
		List<Merchant> list = query.list() ;
		/*List<Merchant> list = findAll() ;*/
		System.out.println(list.size()) ;
		for(Merchant merchant : list){
			if(merchant.getUsername().equals(username)){
				System.out.println("找到");
				return merchant ;
			}
		}
		return null ;
	}

	@Override
	public Set<Goods> findGoodss(Merchant m) {
		return m.getGoodss() ;
	}

	@Override
	public Set<MerchantAddress> findAddress(Merchant m) {
		return m.getMerchantAddress() ;
	}

	@Override
	public MerchantInfor findInfor(Merchant m) {
		return m.getMerchantInfor() ;
	}

	@Override
	public Set<MerchantOrder> findOrders(Merchant m) {
		return m.getMerchantOrder() ;
	}

	@Override
	public boolean saveGoods(Integer id, Goods goods) {
		Session session = getSession() ;
		Merchant merchant = (Merchant) session.get(Merchant.class, id) ;
		
		goods.setMerchant(merchant) ;
		merchant.getGoodss().add(goods) ;
		
		session.save(merchant) ;
		session.save(goods) ;
		
		//session.beginTransaction().commit() ;
		return true ;
	}

	@Override
	public boolean saveAddress(Integer id, MerchantAddress add) {
		Session session = getSession() ;
		Merchant merchant = (Merchant) session.get(Merchant.class, id) ;
		
		add.setMerchant(merchant) ;
		merchant.getMerchantAddress().add(add) ;
		
		session.save(merchant) ;
		session.save(add) ;
		
		return true ;
	}

	@Override
	public boolean saveInfor(Integer id, MerchantInfor infor) {
		Session session = getSession() ;
		Merchant merchant = (Merchant) session.get(Merchant.class, id) ;
		
		infor.setMerchant(merchant) ;
		merchant.setMerchantInfor(infor) ;
		
		session.save(merchant) ;
		session.save(infor) ;
		
		return true ;
	}

	@Override
	public boolean saveOrders(Integer id, MerchantOrder order) {
		Session session = getSession() ;
		Merchant merchant = (Merchant) session.get(Merchant.class, id) ;
		
		order.setMerchant(merchant) ;
		merchant.getMerchantOrder().add(order) ;
		
		session.save(merchant) ;
		session.save(order) ;
		
		return true ;
	}

	

}
